/**
 * MIT License
 * 
 * Copyright (c) 2017 CaiDongyu
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.tunnel.client.task;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.tunnel.client.tcp.TcpDataSenderManager;
import com.tunnel.common.util.LogUtil;

import io.netty.channel.ChannelHandlerContext;

public class TcpTaskManager {

	private static ExecutorService THREAD_POOL = Executors.newCachedThreadPool();
	private static Map<String,TcpTask> TASK_MAP = new HashMap<>();
	
	public static Set<String> getConnectionIdSet(){
		synchronized (TASK_MAP) {
			Set<String> keySet = TASK_MAP.keySet();
			Set<String> copySet = new HashSet<>();
			copySet.addAll(keySet);
			return copySet;
		}
	}
	
	public static TcpTask getTask(String connectionId){
		synchronized (TASK_MAP) {
			return TASK_MAP.get(connectionId);
		}
	}
	
	public static void newTask(int portIndex, byte[] connectionIdBytes, ChannelHandlerContext ctx){
		TcpTask task = new TcpTask(portIndex, connectionIdBytes, ctx);
		synchronized(TASK_MAP){
//			LogUtil.log("add task："+task.getRequestId());
			TASK_MAP.put(task.getConnectionId(),task);
		}
		THREAD_POOL.execute(task);
	}

	public static void sendData2App(String connectionId,byte[] datas){
		TcpTask task = TASK_MAP.get(connectionId);
		if(task == null){
			synchronized(TASK_MAP){
				//尝试10次，如果实在没有，就算了
				for(int i=0;i<10;i++){
					task = TASK_MAP.get(connectionId);
					if(task != null){
						break;
					}
					try {
						Thread.sleep(10);//等待10毫秒
					} catch (Exception e) {}
				}
			}
		}
		if(task != null){
			TcpDataSenderManager.commitData(task, datas);
		}else{
			LogUtil.log("task null");
		}
	}
	
	public static void stopTask(String connectionId){
		synchronized(TASK_MAP){
			if(TASK_MAP.containsKey(connectionId)){
//				LogUtil.log("ready stop task："+connectionId);
				TcpTask tunnelAppTask = TASK_MAP.remove(connectionId);
				tunnelAppTask.cancelTask();
			}
		}
	}
	
	public static void stopTask(){
		synchronized(TASK_MAP){
			for(TcpTask task:TASK_MAP.values()){
//				LogUtil.log("ready stop task："+task.getRequestId());
				task.cancelTask();
			}
			TASK_MAP.clear();
		}
	}
}
